import { Context, Next } from 'koa'
import checkWhetherNeedAuth from './checkWhetherNeedAuth'

export default async (ctx: Context, next: Next) => {
	const isNoLogin = checkWhetherNeedAuth(ctx.path)
	if (isNoLogin) return next()
	const token = ctx.request.header.token
	if (!token) return ctx.error({ code: 401, msg: '无权访问或路径不存在' })

	if (token === '6'.repeat(32)) {
		ctx.userInfo = {
			id: 0,
			phone: '13790000000',
			name: '测试',
			createTime: '0'
		}
		return next()
	}

	// const { uid } = await ctx.db.selectOne(`SELECT uid FROM login WHERE token="${token}"`)
	// const revokeToken = () => ctx.db.update(`UPDATE login SET isVaild=0 WHERE uid=${uid}`)

	const userAgent = ctx.request.header['user-agent']
	const userIp = ctx.request.ip
	const loginInfo = await ctx.db.selectOne(`SELECT * FROM login WHERE token="${token}"`)
	if (!loginInfo) return ctx.error({ code: 401, msg: 'TOKEN 不存在' })
	if (!loginInfo.isVaild) return ctx.error({ code: 401, msg: '登录失效，请重新登录' })
	// if (loginInfo.userIp !== userIp) return ctx.error({ code: 401, msg: '用户IP异常' })
	if (loginInfo.userAgent !== userAgent) return ctx.error({ code: 401, msg: '用户登录环境异常' })
	const userInfo = await ctx.db.selectOne(`SELECT id, phone, name, createTime FROM user WHERE id=${loginInfo.uid}`)
	ctx.userInfo = userInfo
	await next()
}
